package com.corpgovernment.organization.controller;

import cn.hutool.core.util.ObjectUtil;
import com.corpgovernment.api.basic.request.MbUserDeviceRequest;
import com.corpgovernment.api.basic.request.UpdatePasswordRequest;
import com.corpgovernment.api.basic.request.UserLoginRequest;
import com.corpgovernment.api.basic.vo.UserLoginResponseVo;
import com.corpgovernment.api.organization.bo.GetUserInfoRequestBO;
import com.corpgovernment.api.organization.model.message.SendMsgRequest;
import com.corpgovernment.api.organization.model.user.login.*;
import com.corpgovernment.common.apollo.BasicManageApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.base.Page;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.common.utils.Md5Util;
import com.corpgovernment.organization.controller.request.ChangeBindPhoneRequest;
import com.corpgovernment.organization.controller.request.ChangeStaffPhoneRequest;
import com.ctrip.corp.obt.generic.core.context.UserInfoContext;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.db.MbUserLogin;
import com.corpgovernment.organization.model.login.ResetPwdRequestVo;
import com.corpgovernment.organization.service.IUserLoginService;
import com.corpgovernment.organization.vo.UserLoginRequestVO;
import com.corpgovernment.organization.vo.UserLoginVO;
import com.corpgovernment.organization.vo.tenant.SearchTenantInfoRequestVO;
import com.corpgovernment.organization.vo.tenant.SearchTenantInfoResponseVO;
import com.ctrip.corp.obt.auth.client.annotation.NoAuthPath;
import com.ctrip.corp.obt.auth.client.handler.token.JwtTokenHandler;
import com.ctrip.corp.obt.auth.utils.OIDCUtils;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import static com.corpgovernment.api.basic.metadata.ELoginStatus.NO_TOKEN;
import static com.ctrip.corp.obt.generic.core.context.RequestContext.getCurrentContext;

/**
 * 用户登录controller
 *
 * @author jhxue
 */
@RequestMapping(value = "/userlogin")
@RestController
public class UserLoginController {

	@Autowired
	private IUserLoginService userLoginService;
	@Autowired
	private JwtTokenHandler jwtTokenHandler;

	/**
	 * 查询
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public JSONResult<ListUserLoginResponse> list(@RequestBody ListUserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		if (request.getUserLogin() == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "userLogin");
		}
		ListUserLoginResponse response = new ListUserLoginResponse();
		List<MbUserLogin> list = userLoginService.list(this.convert(request.getUserLogin()));
		response.setUserLoginList(this.convert(list));
		return JSONResult.success(response);
	}

	/**
	 * 根据主键更新
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/update")
	public JSONResult<Boolean> update(@RequestBody UpdateUserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		if (request.getUserLogin() == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "userLogin");
		}
		return JSONResult.success(userLoginService.update(this.convert(request.getUserLogin())));
	}


	/**
	 * 账号登录(前台/后台)
	 *
	 * @param request 账号登录请求
	 * @return 账号登录结果
	 */
	@PostMapping("login")
	@NoAuthPath
	public JSONResult<UserLoginResponseVo> login(@RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.login(request));
	}

	@PostMapping("saveDeviceInfo")
	public JSONResult<Boolean> updateDeviceId(BaseUserInfo userInfo, @RequestBody MbUserDeviceRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.updateDeviceId(userInfo, request));
	}
	/**
	 * 确认身份登录(前台)
	 *
	 * @param request 确认身份登录请求
	 * @return 确认身份结果
	 */
	@PostMapping("confirmLogin")
	@NoAuthPath
	public JSONResult<UserLoginResponseVo> confirmLogin(@RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		if (StringUtils.isBlank(request.getDeptId()) && StringUtils.isBlank(request.getCorpId())) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "deptId|CorpId");
		}

		Supplier<CorpBusinessException> commonExceptionSupplier = () -> new CorpBusinessException(OrganizationResponseCodeEnum.CUSTOM_CONTENT, NO_TOKEN.getDesc());
		request.setToken(Optional.ofNullable(getCurrentContext().getRequest().getHeader("token")).orElseThrow(commonExceptionSupplier));
		request.setSource(Optional.ofNullable(getCurrentContext().getRequest().getHeader("source")).orElseThrow(commonExceptionSupplier));
		return JSONResult.success(userLoginService.confirmLogin(request));
	}

	/**
	 * 发送登录验证码(前/后台)
	 *
	 * @param request 发送登录验证码请求
	 * @return 发送登录验证码结果
	 */
	@PostMapping("/sendMsgCode")
	public JSONResult<String> sendMsgCode(@Validated(MbUserLoginVo.SendLoginMsgCodeValid.class) @RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.sendMsgCode(request));
	}

	/**
	 * 验证码登录(前/后台)
	 *
	 * @param request 验证码登录请求
	 * @return 验证码登录结果
	 */
	@PostMapping("validateMsgCode")
	public JSONResult<UserLoginResponseVo> validateMsgCode(@Validated(MbUserLoginVo.SmsLoginValid.class) @RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.validateMsgCode(request));
	}


	/**
	 * 验证更新密码
	 *
	 * @param uid
	 * @param request
	 * @return
	 */
	@PostMapping("/validateUpdatePwd")
	public JSONResult<UserLoginResponseVo> validateUpdatePwd(String uid, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		UserLoginResponseVo response = new UserLoginResponseVo();
		response.setValidateToken(userLoginService.validateUpdatePwd(uid, request.getPwd()));
		return JSONResult.success(response);
	}

	/**
	 * 根据原始密码修改密码
	 *
	 * @param baseUserInfo 用户基本信息
	 * @param request      修改密码请求
	 * @return 密码修改结果
	 */
	@PostMapping("/updatePwd")
	public JSONResult<Boolean> updatePwd(BaseUserInfo baseUserInfo, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.updatePwd(baseUserInfo, request));
	}

	/**
	 * 根据原始密码修改密码(改密后立即登录)
	 *
	 * @param baseUserInfo 用户基本信息
	 * @param request      修改密码请求
	 * @return 密码修改结果
	 */
	@PostMapping("updatePwdLogin")
	public JSONResult<UserLoginResponseVo> updatePwdLogin(BaseUserInfo baseUserInfo, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.updatePwdLogin(baseUserInfo, request));
	}

	/**
	 * 根据原始密码修改密码（含管理员）
	 */
	@PostMapping("/validateUpdatePassword")
	public JSONResult<UserLoginResponseVo> validateUpdatePassword(@RequestBody UpdatePasswordRequest request, String uid) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		request.setUid(uid);
		return JSONResult.success(userLoginService.validateUpdatePassword(request));
	}

	/**
	 * 根据原始密码修改密码（含管理员）
	 */
	@PostMapping("/updatePassword")
	public JSONResult<Boolean> updatePassword(String uid, @RequestBody UpdatePasswordRequest request,BaseUserInfo userInfo) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		request.setUid(uid);
		return JSONResult.success(userLoginService.updatePassword(request,userInfo));
	}

	/**
	 * 根据原始密码修改密码（含管理员）
	 */
	@PostMapping("/resetPassword")
	public JSONResult<Boolean> resetPassword(@RequestBody UpdatePasswordRequest request) {
		userLoginService.resetPwdByUid(request.getUid());
		return JSONResult.success(true);
	}

	/**
	 * 发送重置密码短信(前台/后台)
	 *
	 * @param request 发送重置密码短信请求
	 * @return 短信发送结果
	 */
	@PostMapping("/sendResetPwdMsgCode")
	public JSONResult<String> sendResetPwdMsgCode(@Validated(MbUserLoginVo.SendFindPwdMsgCode.class) @RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.sendResetPwdMsgCode(request));
	}

	/**
	 * 验证重置密码短信验证码
	 *
	 * @param request 验证重置密码短信验证码请求
	 * @return 验证结果
	 */
	@PostMapping("/validateResetPwdMsgCode")
	public JSONResult<UserLoginResponseVo> validateResetPwdMsgCode(@Validated(MbUserLoginVo.FindPwdMsgCodeValid.class) @RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.validateResetPwdMsgCode(request));
	}

	/**
	 * 根据重置验证码验证结果重置密码
	 *
	 * @param request 重置验证码验证结果重置密码
	 * @return 重置密码结果
	 */
	@PostMapping("resetPwdMsgCode")
	public JSONResult<UserLoginResponseVo> resetPwdMsgCode(@Validated(UserLoginRequest.ResetPwdValid.class) @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.resetPwdMsgCode(request));
	}

	/**
	 * 创建或更新前台登录用户信息
	 *
	 * @param request 创建或更新前台登录用户信息请求
	 * @return 创建或更新前台登录用户信息结果
	 */
	@PostMapping("saveOrUpdateUserLogin")
	public JSONResult<Boolean> saveOrUpdateUserLogin(@RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.saveOrUpdate(request, false));
	}

	/**
	 * 创建或更新后台登录用户信息
	 *
	 * @param request 创建或更新后台登录用户信息请求
	 * @return 创建或更新后台登录用户信息结果
	 */
	@PostMapping("saveOrUpdateBgUserLogin")
	public JSONResult<Boolean> saveOrUpdateBgUserLogin(@RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.saveOrUpdate(request, true));
	}

	/**
	 * 根据uid获取登录用户信息
	 *
	 * @param request 获取登录用户信息请求
	 * @return 登录用户信息
	 */
	@PostMapping("/getUserLogin")
	public JSONResult<MbUserLoginVo> getUserLogin(@RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		if (StringUtils.isBlank(request.getUid())) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "uid");
		}
		MbUserLogin userLogin = userLoginService.getByUid(request.getUid());
		if (userLogin == null) {
			return JSONResult.errorMsg(1001, "未查到用户");
		}
		return JSONResult.success(this.convert(userLogin));
	}

	/**
	 * 删除用户
	 *
	 * @param uid
	 * @return
	 */
	@RequestMapping("/deleteUserLogin")
	public JSONResult<Boolean> deleteUserLogin(@RequestParam("uid") String uid) {
		if (StringUtils.isBlank(uid)) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "uid");
		}
		boolean flag = userLoginService.deleteByUid(uid);
		return flag ? JSONResult.ok() : JSONResult.errorMsg(1001211, "删除失败");
	}

	/**
	 * 登出
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/logout")
	@NoAuthPath
	public JSONResult<Boolean> logout(@RequestBody MbUserLoginVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		String token = OIDCUtils.obtainAuthorization(RequestContext.getCurrentContext().getRequest());
		if (StringUtils.isBlank(token)) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.VALIDATE_TOKEN_IS_NULL);
		}
		Map<String, Object> userInfo = jwtTokenHandler.parseTokenPayload(token);
		return JSONResult.success(userLoginService.logout(userInfo, request.getUuid(), request.getDeviceId()));
	}

	/**
	 * 更新用户状态
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/updateUserStatus")
	public JSONResult<Boolean> updateUserStatus(@RequestBody UserLoginRequestVO request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		BaseUserInfo userInfo = UserInfoContext.getContextParams(BaseUserInfo.class);

		return JSONResult.success(userLoginService.updateUserStatus(request, userInfo));
	}


	/**
	 * 发送解绑短信
	 *
	 * @param userInfo
	 * @param request
	 * @return
	 */
	@RequestMapping("/sendUnbindMsg")
	public JSONResult<String> sendUnbindMsg(BaseUserInfo userInfo, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.sendUnbindMsg(userInfo.getAccountName(), request.getPhoneNum(), request.getCountryCode()));
	}

	/**
	 * 解绑手机
	 *
	 * @param userInfo
	 * @param request
	 * @return
	 */
	@RequestMapping("/unBindPhone")
	public JSONResult<String> unBindPhone(BaseUserInfo userInfo, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.unBindPhone(userInfo.getAccountName(), request.getPhoneNum(), request.getMsgCode(), request.getCountryCode(), userInfo.getSource()));
	}

	/**
	 * 发送修改员工手机号验证码
	 * @param userInfo
	 * @param request
	 * @return
	 */
	@RequestMapping("/sendUploadStaffMsgCode")
	public JSONResult<String> sendUploadStaffMsgCode(BaseUserInfo userInfo, @RequestBody ChangeStaffPhoneRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.sendUploadStaffMsgCode(userInfo.getAccountName(), request.getPhoneNum(), request.getCountryCode(), userInfo.getSource()));
	}

	/**
	 * 确认修改员工手机号
	 * @param userInfo
	 * @param request
	 * @return
	 */
	@RequestMapping("/checkUploadStaffMsgCode")
	public JSONResult<Boolean> checkUploadStaffMsgCode(BaseUserInfo userInfo, @RequestBody ChangeStaffPhoneRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.checkUploadStaffMsgCode(userInfo.getAccountName(), request.getPhoneNum(), request.getSmsCode(), request.getIsSyncLoginPhone(), request.getCountryCode(), userInfo.getSource()));
	}

	/**
	 * 确认修改员工手机号
	 * @param userInfo
	 * @return
	 */
	@RequestMapping("/testNetty")
	public JSONResult<Boolean> testNetty(BaseUserInfo userInfo) {

		return JSONResult.success(userLoginService.testNetty(userInfo.getAccountName()));
	}

	/**
	 * 换绑手机
	 *
	 * @param userInfo
	 * @param request
	 * @return
	 */
	@RequestMapping("/changeBindPhone")
	public JSONResult<UserLoginResponseVo> changeBindPhone(BaseUserInfo userInfo, @RequestBody ChangeBindPhoneRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.changeBindPhone(userInfo.getAccountName(),
				request.getUnBindMsgCode(),
				request.getUnBindCountryCode(),
				request.getUnBindPhoneNum(),
				request.getBindMsgCode(),
				request.getBindCountryCode(),
				request.getBindPhoneNum(),
				userInfo.getSource()));
	}

	/**
	 * 发送绑定手机号验证码  需登录状态
	 *
	 * @param userInfo 用户基本信息
	 * @param request  发送绑定手机号验证码请求
	 * @return 发送绑定手机号验证码结果
	 */
	@PostMapping("/sendBindMsgCode")
	public JSONResult<String> sendBindMsgCode(BaseUserInfo userInfo, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.sendBindMsgCode(userInfo.getAccountName(), request.getPhoneNum(), request.getCountryCode(), userInfo.getBgUser()));
	}

	/**
	 * 验证绑定手机验证码 需登录状态
	 *
	 * @param userInfo 用户基本信息
	 * @param request  验证绑定手机验证码请求
	 * @return 绑定解果
	 */
	@PostMapping("/bindPhone")
	public JSONResult<Boolean> bindPhone(BaseUserInfo userInfo, @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.bindPhone(userInfo, request));
	}

	/**
	 * 供应商修改密码发送验证码使用
	 *
	 * @param request 发送验证码请求
	 * @return 发送结果
	 */
	@RequestMapping("/sendSms")
	public JSONResult<String> sendSmsMsg(@RequestBody SendMsgRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		userLoginService.sendSmsMsg(request);
		return BasicManageApollo.getZtSmsSend() ? JSONResult.ok() : JSONResult.success(request.getCode());
	}

	/**
	 * 重置密码(admin管理后台)
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/resetPwd")
	public JSONResult<String> resetPwd(@Validated @RequestBody ResetPwdRequestVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		return JSONResult.success(userLoginService.resetPwdByUid(request.getUid()));
	}

	/**
	 * 根据用户手机查询用户信息
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/getMbUserByPhoneAndCountryCode")
	public JSONResult<UserLoginVO> getMbUserByPhoneAndCountryCode(@Validated(UserLoginRequest.GetMbUserByPhoneAndContuntryCodeValid.class) @RequestBody UserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		MbUserLogin userLogin = userLoginService.getByPhoneNumAndCountryCodeAndBgUser(request.getPhoneNum(), request.getCountryCode(), false);
		return JSONResult.success(UserLoginVO.convertFrom(userLogin));
	}

	/**
	 * 修改密码
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/changePassword")
	public JSONResult<String> changePassword(@RequestBody ResetPwdRequestVo request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		if (StringUtils.isBlank(request.getUid())) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_NULL);
		}
		if (request.getPassword().length() < 6) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PASSWORD_SPECIFICATION_ERROR);
		}
		MbUserLogin userLogin = userLoginService.getByUid(request.getUid());
		userLogin.setPwd(Md5Util.getDeepMd5Msg(userLogin.getUid(), request.getPassword()));
		userLoginService.updatePwd(userLogin);
		return JSONResult.ok();
	}

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/pageByCondition")
	public JSONResult<Page<UserInfoType>> pageByCondition(@RequestBody PageByConditionRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "request");
		}
		return JSONResult.success(userLoginService.pageByCondition(request));
	}

	/**
	 * 保存账号信息
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/save")
	public JSONResult<Boolean> save(@RequestBody SaveUserLoginRequest request) {
		if (request == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_NULL);
		}
		if (request.getUserLogin() == null) {
			throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_INFO_DONT_EXISTS);
		}
		return JSONResult.success(userLoginService.save(request.getUserLogin()));
	}

	/**
	 * 判断refreshToken是否失效
	 *
	 * @param refreshToken
	 * @return
	 */
	@PostMapping("/refresh/{refreshToken}")
	@NoAuthPath
	public JSONResult<UserLoginResponseVo> refresh(@PathVariable(value = "refreshToken") String refreshToken) {
//		return userLoginService.refresh(refreshToken).map(JSONResult::success);
		return JSONResult.success(userLoginService.refresh(refreshToken));
	}

	/**
	 * 获取用户信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getUserInfo")
	public JSONResult<BaseUserInfo> getUserInfo(@RequestBody @Valid GetUserInfoRequestBO request){
		return JSONResult.success(userLoginService.getUserInfo(request));
	}

	/**
	 * 获取用户信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/v2/getUserInfo")
	public JSONResult<BaseUserInfo> getUserInfoV2(@RequestBody @Valid GetUserInfoRequestBO request){
		return JSONResult.success(userLoginService.getUserInfoV2(request));
	}

	/**
	 * 查询租户信息
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/searchTenantInfo")
	public JSONResult<SearchTenantInfoResponseVO> searchTenantInfo(@RequestBody SearchTenantInfoRequestVO request) {
		return JSONResult.success(userLoginService.searchTenantInfo(request));
	}

	/**
	 * 数据转换（entity转vo）
	 *
	 * @param source
	 * @return
	 */
	private MbUserLoginVo convert(MbUserLogin source) {
		if (source == null) {
			return null;
		}
		MbUserLoginVo target = new MbUserLoginVo();
		BeanUtils.copyProperties(source, target);
		return target;
	}

	/**
	 * 数据转换（soa转entity）
	 *
	 * @param source
	 * @return
	 */
	private MbUserLogin convert(UserLoginType source) {
		if (source == null) {
			return null;
		}
		MbUserLogin target = new MbUserLogin();
		BeanUtils.copyProperties(source, target);
		target.setStatus(source.getIsEnabled());
		return target;
	}

	/**
	 * 数据转换（entity list转soa list）
	 *
	 * @param sourceList
	 * @return
	 */
	private List<UserLoginType> convert(List<MbUserLogin> sourceList) {
		if (CollectionUtils.isEmpty(sourceList)) {
			return null;
		}
		return sourceList.stream().map(e -> {
			if (e == null) {
				return null;
			}
			UserLoginType target = new UserLoginType();
			BeanUtils.copyProperties(e, target);
			return target;
		}).collect(Collectors.toList());
	}
}
